package com.googlecode.gwtbb.server.dao;

import com.googlecode.gwtbb.client.shared.util.StringUtils;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

import java.sql.SQLException;

/**
 * Based on EnumTypeHandler from:
 * http://opensource.atlassian.com/confluence/oss/display/IBATIS/How+do+I+use+a+Custom+Type+Handler+with+complex+property+or+Type+Safe+Enumeration
 *
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 28, 2008
 */
public abstract class EnumTypeHandler<E extends Enum> implements TypeHandlerCallback {
	private Class<E> enumClass;

	public EnumTypeHandler(Class<E> enumClass) {
		this.enumClass = enumClass;
	}

	public Object getResult(ResultGetter getter) throws SQLException {
		return valueOf(getter.getString());
	}

	@SuppressWarnings("unchecked")
	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
		setter.setString(parameter != null ? StringUtils.constToVariableStyle(((E)parameter).name()) : null);
	}

	public Object valueOf(String s) {
		return s != null ? Enum.valueOf(enumClass, StringUtils.variableToConstStyle(s)) : null;
	}
}
